package cn.kunakun.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.kunakun.common.pojo.PageVO;
import cn.kunakun.utils.ImageUtils;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.bson.Document;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.kunakun.mapper.ArticleMapper;
import cn.kunakun.pojo.Article;
import tk.mybatis.mapper.entity.Example;

@Service
public class ArticleService extends BaseService<Article> {
    /**
     * logger
     */
    private static final Logger logger = LoggerFactory.getLogger(ArticleService.class);
    public static final String BASE64_PREFIX = "data:image/png;base64,";
    @Autowired
    MongoDatabase mongoDatabase;
    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    AsynHttpService httpService;
    @Autowired
    QiniuService qiniuService;

    /**
     * @return
     * @date 2018年6月2日下午2:32:49
     * @auth YangKun
     */
    public PageInfo<Article> wapHomeArticle() {
        PageHelper.startPage(1, 2);
        Example example = new Example(Article.class);
        example.orderBy("create_time").desc();
        List<Article> list = articleMapper.selectByExample(example);
        return new PageInfo<Article>(list);
    }

    public String querymArticleContentById(Long id) {
        MongoCollection<Document> collection = mongoDatabase.getCollection("t_article");
        BasicDBObject bson = new BasicDBObject("id", id);
        FindIterable<Document> find = collection.find(bson);
        for (Document doc : find) {
            return doc.getString("content");
        }
        return null;
    }

    public void insertMongoArticle(Article article) {
        try {
            MongoCollection<Document> collection = mongoDatabase.getCollection("t_article");
            Document doc = new Document();
            doc.put("id", article.getId());
            doc.put("content", article.getContent());
            collection.insertOne(doc);
        } catch (Exception e) {
            logger.error("{}插入失败", article.getId());
        }
        return;
    }

    public void delMongoArticle(Long id) {
        try {
            MongoCollection<Document> collection = mongoDatabase.getCollection("t_article");
            BasicDBObject bson = new BasicDBObject("id", id);
            collection.deleteOne(bson);
        } catch (Exception e) {
            logger.error("{}删除失败", id);
        }
        return;
    }

    public PageInfo<Article> queryTitleAndTimeByTime(PageVO pageVO, Article article) {
        PageHelper.startPage(pageVO.getPage(), pageVO.getRows());
        List<Article> list = articleMapper.queryTitleAndTimeByTime(article);
        return new PageInfo<Article>(list);
    }

    /**
     * 替换图片
     *
     * @Author YangKun
     * @Date 2018/11/1
     */
    public Article replaceImg(Article article) {
        org.jsoup.nodes.Document document = Jsoup.parse(article.getContent());
        //XXX 先删除  cnblogs_code_toolbar   cnblogs_code_toolbar
        document.select(".cnblogs_code_toolbar").remove();
        Elements imgs = document.select("img");
        //判断是不是我的图片
        ArrayList<Pair> newImageSrcList = Lists.newArrayList();
        for (Element img : imgs) {
            String src = img.attr("src");
            //包含我的这个src
            if (StringUtils.contains(src, "kunakun.6655.la")) {
            } else {
                InputStream inputStream;
                //上传到七牛
                try {
                    if (StringUtils.contains(src, BASE64_PREFIX)) {
                        logger.debug("发现base64的正在替换S");
                        inputStream = ImageUtils.generateImage(src.replace(BASE64_PREFIX, ""));
                    } else {
                        inputStream = httpService.doGetInputStream(src);
                    }
                    //上传到七牛云里面
                    Map<String, Object> resultMap = qiniuService.uploadInputStream(inputStream);
                    //得到七牛云返回的url
                    String qiniu_path = resultMap.get("qiniu_path").toString();
                    Pair<String, String> pair = Pair.of(src, qiniu_path);
                    newImageSrcList.add(pair);
                } catch (Exception e) {
                    logger.error(Throwables.getStackTraceAsString(e));
                }
            }
        }
        logger.debug("已经外面图片都替换OK了");
        String content = article.getContent();
        for (Pair item : newImageSrcList) {
            String left = item.getLeft().toString();
            String right = item.getRight().toString();
            content = StringUtils.replaceAll(content, left, right);
        }
        logger.debug("替换全部完成,重新设置content");
        org.jsoup.nodes.Document parse = Jsoup.parse(content);
        parse.select(".cnblogs_code_toolbar").remove();
        logger.debug("删掉博客园的复制代码的那个方块完成");
        article.setContent(parse.toString());

        return article;
    }

    public void deleteQiNiu(String id) {
        String content = this.querymArticleContentById(Long.valueOf(id));
        org.jsoup.nodes.Document document = Jsoup.parse(content);
        Elements imgs = document.select("img");
        for (Element img : imgs) {
            String src = img.attr("src");
            if (src.contains("kunakun.6655.la")) {
                logger.debug("开始删除骑牛图片->{}", src);
                String substring = src.substring(23);
                String key = StringUtils.substringBefore(substring, "?");
                qiniuService.deleteImage(key);
            }
        }

    }

    public static void main(String[] args) {
//        String a = "http://kunakun.6655.la/abaa5540b21f4818a9251063dd4cd38b.jpg?imageMogr2/quality/70/format/jpg";
//        String substring = a.substring(23);
//        String key = StringUtils.substringBefore(substring, "?");
//        System.out.println(key);

        String str = "";
        InputStream inputStream = ImageUtils.generateImage(str);

    }
}
